package validator;

import exceptions.InvalidIPAdressException;

/**
 * Implements a validator of IPs
 * 
 * @author Alexandre, Cristovao, Raul, Rodolpho, Tales
 * @version 1.1
 * @milestone Number 2
 */
public class IPValidator {

	/**
	 * Validates the email address
	 * 
	 * @param ip
	 * @throws InvalidIPAdressException
	 */
	public static void validateIP(String ip) throws InvalidIPAdressException {
		// if ((ip.split("\\.")).length != 4) {
		// throw new InvalidIPAdressException("IP invalido.");
		// }
		
		String message = "IP invalido.";

		if (ip == null || ip == "")
			throw new InvalidIPAdressException(message);

		String[] parteIP = ip.replace(".", "-").split("-");

		if (parteIP.length != 4)
			throw new InvalidIPAdressException(message);

		int[] valoresIP = new int[4];

		for (int i = 0; i < 4; i++) {
			try {
				valoresIP[i] = Integer.parseInt(parteIP[i]);
			} catch (NumberFormatException ie) {
				ie.getMessage();
				throw new InvalidIPAdressException(message);
			}

			if (i == 0 && valoresIP[i] < 1)
				throw new InvalidIPAdressException(message);

			if (valoresIP[i] < 0 || valoresIP[i] > 255)
				throw new InvalidIPAdressException(message);
		}
	}
}
